
"""work with the pypi queue"""

import os
import simplejson
import optparse
from urllib2 import urlopen

def main():
    p = optparse.OptionParser(usage='%prog [options] CHANNEL')
    default = 'http://pypi.appspot.com'
    p.add_option('-p', '--pypione', default=default,
            help="URL for Pypione, no trailing slash.  Default: %s" % default)
    p.add_option('-l', '--list-only', action='store_true', 
            help="Just list items to be processed and exit.")
    (options, args) = p.parse_args()
    if len(args) != 1:
        p.error("incorrect usage")
    channel = args[0]
    r = urlopen(options.pypione + '/p/queue/%s/pending/' % channel)
    pending = simplejson.load(r)
    r.close()
    if not pending['successful']:
        print pending
        raise RuntimeError("queue was not successful")
    for item in pending['items']:
        if options.list_only:
            print item['channel'], ":", item['url']
            continue
        r = urlopen(options.pypione + item['url'])
        done = simplejson.load(r)
        r.close()
        print item['channel'], ":", item['url']
        print done

if __name__ == '__main__':
    main()